<template>
  <div >
    <div class="addcomments">
      <textarea maxlength="1000" @change="hehe" v-model="othertextareatexts" class="addcommentstestarea" :style="{height:textareaHeight}"
      :placeholder="fatherpage==0?'请填写试吃报告...':fatherpage==1?'请填写试用报告...':'请编辑'" ></textarea>
      <span class="maxtext" :style="{top:spanHeight}">({{textlength}}/1000)</span>
      <div class="upload" >
        <div  class="flex">
          <div v-for="(item,index) in thumbnailslist.slice(0,fatherpage==0?9:9)" class="picdiv" :key="index" >
            <img v-lazy="item.src.indexOf('imageMogr2')>-1?item.src:(item.src+'?imageMogr2/auto-orient')" class="imgsize" />
            <span class="yl-2red-del deletepic" @click="deletepic(index)"><span class="path1"><span class="path2"><span class="path3"></span></span></span></span>
          </div>
          <div :class="myjiasvg" class="addsvg" v-if="thumbnailslist.length<9">
            <input multiple="multiple" type="file" class="myinput" accept="image/gif, image/jpeg, image/png,image/jpg"
                   @change="createImage($event)" />
            <div style="font-size: 0.2rem" v-if="isupload==true" class="progressvalue">
              <mt-spinner :size="40" type="fading-circle"></mt-spinner>
              <span style="margin-top: -0.5rem;position: absolute;margin-left: -0.38rem">{{progressvalue}}%</span>
            </div>
          </div>
        </div>

      </div>
    </div>
  </div>
</template>
<script>
import axios from "axios";
import api from "src/api/index";
import { Progress as mtProgress, Toast } from "mint-ui";
import { Spinner } from "mint-ui";
import lrz from "lrz";
//获取字符长度
function JHshStrLen(sString) {
  var sStr, iCount, i, strTemp;
  iCount = 0;
  sStr = sString.split("");
  for (i = 0; i < sStr.length; i++) {
    strTemp = escape(sStr[i]);
    if (strTemp.indexOf("%u", 0) == -1) {
      // 是否是汉字
      iCount = iCount + 1;
    } else {
      iCount = iCount + 2;
    }
  }
  return iCount;
}

export default {
  data() {
    return {
      list: [],
      textlength: "0",
      progressvalue: "",
      isupload: "",
      myjiasvg: "yl-2pic",
      othertextareatexts: this.textareatexts,
      textareaHeight: "3rem",
      spanHeight: "3.4rem"
    };
  },
  components: {
    mtProgress,
    Spinner,
    Toast
  },
  props: ["textareatexts", "thumbnailslist","fatherpage"],
  //fatherpage:0试用报告
  mounted() {
    this.getqiuniutoken();
  },
  watch: {
    textareatexts(val, oldval) {
      this.othertextareatexts = val;
    },
    othertextareatexts() {
      if (this.othertextareatexts) {
        let textlength = this.othertextareatexts.length;
        this.textlength = textlength;

        //添加textarea自动增长
        let rowNum = Math.floor(JHshStrLen(this.othertextareatexts) / 52);
        if (rowNum > 8) {
          this.textareaHeight = 3.3 + 0.28 * (rowNum - 8) + "rem";
          this.spanHeight = 3.7 + 0.28 * (rowNum - 8) + "rem";
          this.$emit("changeTextArea");
        }
      } else {
        this.textareaHeight = "3rem";
        this.spanHeight = "3.4rem";

        this.textlength = 0;
      }
    }
  },
  methods: {
    deletepic(index) {
      this.thumbnailslist.splice(index, 1);
      if(this.fatherpage==0){
        if(this.thumbnailslist.length<9){
          this.myjiasvg = "yl-2pic";
        }else{
          this.myjiasvg = "";
        }
      }else{
        if(this.thumbnailslist.length<9){
          this.myjiasvg = "yl-2pic";
        }else{
          this.myjiasvg = "";
        }
      }
    },
    hehe() {
      this.$emit("haha", this.othertextareatexts);
    },
    //上传前压缩
    createImage(event){
      this.myjiasvg = "";
      let file = event.target.files;
      console.log(file)
      let that = this;
      _each(file, (v, i) => {
        //判断图片上传类型
        var tempIndex = v.type.lastIndexOf("/");
        var imgType = v.type.substring(tempIndex+1);
        if(imgType!=="jpg"&&imgType!=="jpeg"&&imgType!=="png"&&imgType!=="gif"){
          that.$toast("不支持的图片类型");
          that.isupload = false;
          that.myjiasvg = "yl-2pic";
          return
        }

        //100k以上压缩
        if(v.size<102400){
            that.isupload = true;
            that.upload(v);
        }else{
           that.isupload = true;
          lrz(v, { quality: 0.8 }).then(function(rst) {
              v=rst.file;
              that.upload(v);
              return rst;
            }).catch(function (err) {
                // 处理失败会执行
                console.log(err)
            })
            .always(function () {
                // 不管是成功失败，都会执行
            });
        }
      })
    },
    upload(v) {
        const self = this;
        const fd = new window.FormData();
        fd.append("token", this.token);
        fd.append("file", v);
        axios
          .post("https://upload-z2.qiniup.com", fd, {
            headers: {
              "Content-Type": "multipart/form-data",
              "Access-Control-Allow-Origin": "*",
              "Access-Control-Allow-Headers": "Origin, X-Requested-With, Content-Type, Accept"
            },
            timeout: 40000,
            onUploadProgress(e) {
              const isLt10M = e.total / 1024 / 1024 > 20;
              self.progressvalue = parseFloat(e.loaded / e.total * 100).toFixed(
                2
              );
              if (isLt10M) {
                this.$toast("您上传的图片大于20M,请上传小于20M的图片!!");
                 this.isupload = false;
              }
            }
          })
          .catch(error => {
            this.isupload = false;
            this.$toast("图片上传超时!!");
          })
          .then(res => {
            var newimg = new Object();
            var thumbnailslistimg = new Object();
            newimg.src = "https://youlingqinius.wonderlandnet.cn/" + res.data.key;
            thumbnailslistimg.src =
              "https://youlingqinius.wonderlandnet.cn/" + res.data.key;
            let qiniuimgurl =
              "https://youlingqinius.wonderlandnet.cn/" + res.data.key + "?imageInfo";
            axios.get(qiniuimgurl).then(res => {
              if (res.status == "200") {
                newimg.w = res.data.width;
                thumbnailslistimg.w = res.data.width;
                newimg.h = res.data.height;
                thumbnailslistimg.h = res.data.height;
                if(this.thumbnailslist.length>8){
                  this.$toast('最多上传9张图片！')
                  return
                }
                this.thumbnailslist.push(thumbnailslistimg);
                this.list.push(newimg);
                this.$emit("commentpics", this.list);
                this.myjiasvg = "yl-2pic";
                this.isupload = false;
              }
            }).catch(error => {
               this.isupload = false;
            });
          });
    },
    getqiuniutoken() {
      api.Queryuploadtoken({})
        .then(res => {
          if (res.success) {
            this.token = res.token;
          }
        })
        .catch(error => {
        });
    }
  }
};
</script>
<style lang="less" scoped>
* {
  -webkit-user-select: auto;
  -user-select: auto;
}
.addcomments {
  width: 100%;
  min-height: 4.65rem;
  background-color: white;
  position: relative;
  color: #999999;
  font-family: "PingFangSC Regular";
  font-size: 0.26rem;
}
.addcommentstestarea {
  width: 6.9rem;
  border: none;
  padding: 0;
  color: #999999;
  font-size: 0.26rem;
  margin: 0.3rem 0.3rem 0 0.3rem;
}
.maxtext {
  position: absolute;
  right: 0.3rem;
  color: #999999;
  font-size: 0.24rem;
  display: inline-block;
  font-family: Arial;
}
.upload {
  width: 7.3rem;
  display: flex;
  flex-wrap: wrap;
  top: 3.8rem;
  background-color: white;
  padding: 0.4rem 0.1rem 0.3rem 0.3rem;
  max-height: 7.2rem;
}
.upload .flex{
  flex-wrap:wrap;
}
.imgsize {
  width: 1rem;
  height: 1rem;
  margin-right: 0.15rem;
  margin-top: 0.2rem;
  overflow: scroll;
}
.addsvg {
  width: 1rem;
  height: 1rem;
  position: relative;
  text-align: center;
  line-height: 1rem;
  font-size: 1rem;
  color: #cccccc;
  margin-top: 0.2rem;
}
.addsvg input {
  opacity: 0;
}
.myinput {
  width: 1rem;
  height: 1rem;
  position: absolute;
  bottom: 0rem;
  left: 0rem;
}
.deletepic {
  position: absolute;
  top: 0.05rem;
  right: 0.1rem;
  font-size: 0.3rem;
}
.picdiv {
  position: relative;
}
.progressvalue {
  position: absolute;
  left: 0.6rem;
  top: 0.4rem;
  height: 1.3rem;
}
</style>
